import pymysql

class MysqlClient:
    
    def __init__(self, host, port, database, username, password,charset='utf8'):
        self.con = pymysql.connect(host=host, port=port, database=database, user=username, password=password, charset=charset)
        
            
    def insert_sql(self, sql):
        try:
            cursor = self.con.cursor()
            cursor.execute(sql)
            self.con.commit()
            return True
        except Exception as e:
            print(e)
            self.con.rollback()
        finally:
            cursor.close()
    
    def delete_sql(self, sql):
        try:
            cursor = self.con.cursor()
            cursor.execute(sql)
            self.con.commit()
            return True
        except Exception as e:
            print(e)
            self.con.rollback()
            return False
        finally:
            cursor.close()
            
    def update_sql(self, sql):
        try:
            cursor = self.con.cursor()
            cursor.execute(sql)
            self.con.commit()
            return True
        except Exception as e:
            print(e)
            self.con.rollback()
            return False
        finally:
            cursor.close()

    def select_sql(self, sql):
        try:
            cursor = self.con.cursor()
            cursor.execute(sql)
            datas = cursor.fetchall()
            return datas
        except Exception as e:
            print(e)
            self.con.rollback()
        finally:
            cursor.close()
                   
if __name__== "__main__":
    client = MysqlClient("192.168.21.2",3307, "zentao", "root", "pass4Zentao")

    result = client.select_sql("select * from zt_user")

    for data in result:
        print(data)
    
    result =client.update_sql("update zt_user set nickname = 'karonickname2' where account = 'karo'")
    print("@@@@ update result:{}".format(result))
    result = client.delete_sql("delete from zt_user where account = 'tester2'")
    print("@@@@ delete result:{}".format(result))
